/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.wizards;


import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.dialogs.ResourceSelectionDialog;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import es.upm.dit.gsi.jadex.customproject.natures.JadexProjectNature;

/**
 * This page allows to select the desired capability file in order to export it to the capabilities repository
 *    
 *  @author Pablo Muñoz
 */

public class ExportToRepositoryWizardPage extends WizardPage {
	private Text capabilityFileText;
	private Button browseCapabilities;
	private Table filesTable;
	private ArrayList<IFile> fileList;
	
	/**
	 * Constructor for ExportToRepositoryWizardPage
	 * 
	 * @param pageName
	 */
	public ExportToRepositoryWizardPage() {
		super("wizardPage");
		setTitle("Export to Repository");
		setDescription("This wizard exports the selected capability to the repository");
	}

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {		
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 3;
		layout.verticalSpacing = 9;
		PlatformUI.getWorkbench().getHelpSystem().setHelp(container, "es.upm.dit.gsi.eclipse.jadex.adfmanager.addExpressionWizard");
		
		GridData gd1 = new GridData(SWT.FILL, SWT.TOP, true, false,1,1);
		GridData gd3 = new GridData(SWT.FILL, SWT.TOP, true, false,3,1);
		
		Label label1 = new Label(container, SWT.NULL);
		label1.setText("Capability:");
		capabilityFileText = new Text(container, SWT.BORDER | SWT.SINGLE);
		capabilityFileText.setLayoutData(gd1);
		capabilityFileText.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				dialogChanged();
			}
		});
		browseCapabilities = new Button(container, SWT.PUSH);
		browseCapabilities.setText("Browse...");
		browseCapabilities.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e) {
				handleBrowse();
			}
		});
		
		Label label2 = new Label(container, SWT.NULL);
		label2.setText("Files to export: ");
		filesTable = new Table (container, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
		filesTable.setLinesVisible (true);
		filesTable.setHeaderVisible (false);
		GridData gd = gd3;
		gd.heightHint = 230;
		filesTable.setLayoutData(gd);
		TableColumn column = new TableColumn(filesTable,SWT.NONE);
		column.setText("files");
		column.pack();
		
		initialize();
		dialogChanged();
		setControl(container);
	}
	
	private void handleBrowse() {
		fileList = new ArrayList<IFile>();
		ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
			    getShell(), new WorkbenchLabelProvider(), new BaseWorkbenchContentProvider());
			dialog.setTitle("Select target Capability");
			dialog.setMessage("Select the target capability file:");
			dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
			dialog.setAllowMultiple(false);
			dialog.addFilter(new ViewerFilter() {				
				@Override
				public boolean select(Viewer viewer, Object parentElement, Object element) {
					if(element instanceof IProject){
						IProject p = (IProject) element;
						try{
							if(p.hasNature(JadexProjectNature.NATURE_ID)){
								return true;
							}
							else{
								return false;
							}
						}
						catch(CoreException e1){
							return false;
						}
					}
					else{
						if(element instanceof IFile){
							IFile file = (IFile) element;
							try{
								if(file.getName().endsWith("capability.xml")){
									return true;
								}
								else{
									return false;
								}
							}
							catch(Exception e1){
								return false;
							}
						}
						
					}
					return true;
				}
			});
			dialog.setValidator(new ISelectionStatusValidator() {
				
				@Override
				public IStatus validate(Object[] selection) {
					if(selection.length == 1){
						if(selection[0] instanceof IFile){
							IFile fileSel = (IFile) selection[0];
							if(fileSel.getName().endsWith("capability.xml")){
								return ValidationStatus.ok();
							}
						}
					}
					return ValidationStatus.error("Invalid selection");
				}
			});
		if (dialog.open() == ResourceSelectionDialog.OK) {
			Object[] result = dialog.getResult();
			IFile f = (IFile) result[0];
			fileList.add(0, f);
			capabilityFileText.setText(f.getRawLocation().toOSString());
			dialogChanged();
			try {
				updateFileList();
			}
			catch(Exception e1){
				e1.printStackTrace();
			}
		}
	}

	/**
	 * Tests if the current workbench selection is a suitable container to use.
	 */
	private void initialize() {
	}

	/**
	 * Ensures that the all text fields are set correctly.
	 */
	private void dialogChanged() {
		updateStatus(null);
	}

	/*
	 * This method is called in order to update the status message 
	 */
	private void updateStatus(String message) {
		setErrorMessage(message);
		setPageComplete(message == null);
	}	
	
	private void updateFileList() throws SAXException, IOException, ParserConfigurationException{
		IFile capabilityFile = fileList.get(0);
			
		if(capabilityFile == null | !capabilityFile.exists()){
			return;
		}
		if(capabilityFileText.getText().length() <= 0){
			return;
		}
		IProject project = capabilityFile.getProject();
		
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(capabilityFile.getRawLocation().toOSString());
		
		Element root = (Element)doc.getElementsByTagName("capability").item(0);
		String capabilityPackage = root.getAttribute("package");
	 
		NodeList plans = doc.getElementsByTagName("plan");		
		
		for(int i = 0; i < plans.getLength() ; i++){
			IFile resource = null;
			Element plan = (Element) plans.item(i);
			Element body = (Element) plan.getElementsByTagName("body").item(0);
			if(body != null){
				String classname = ((Element)body).getAttribute("class");
				if(classname != null & classname.length() > 0){
					/*
					 * Añadir aquí el código para la búsqueda de cada uno
					 * de los ficheros de esas clases. La variable classname NO incluye la
					 * extensión ".java"
					 * 
					 * AHORA MISMO FUNCIONA SOLO SI LOS PLANES ESTÁN EN LA MISMA CLASE QUE LA CAPABILITY OJO!
					 */
					
					resource = (IFile)(project.findMember("/src/main/java/" + capabilityPackage +  "/" + classname + ".java"));
				}
				
			}
			if(resource != null ){
				fileList.add(resource);				
			}	
		}
		
		for(IFile f : fileList){
			TableItem item  = new TableItem(filesTable, SWT.NONE);
			item.setText(f.getProjectRelativePath().toOSString());
		}

	}
	
	
	
	
}